package com.alexwan.nightnote.db;

import java.sql.SQLException;
import java.util.ArrayList;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.util.Log;

/**
 * 文章
 * 
 * @author alexwan
 * 
 */
public class ArticleProvider extends ContentProvider {
	public static final String AUTHORITY = "com.alexwan.nightnote.provider.db.Articles";
	public static final String TABLE_NAME = "articles";
	public static final Uri CONETNT_URI = Uri.parse("content://" + AUTHORITY
			+ "/" + TABLE_NAME);
	// UriMatcher类型的静态字段是用来匹配传入到ContentProvider中的Uri的类
	private static final UriMatcher URI_MATCHER = new UriMatcher(
			UriMatcher.NO_MATCH);
	private static final int MESSAGES = 1;
	private static final int MESSAGE_ID = 2;
	static {
		URI_MATCHER.addURI(AUTHORITY, "articles", MESSAGES);
		URI_MATCHER.addURI(AUTHORITY, "articles/#", MESSAGE_ID);
	}
	private SQLiteOpenHelper mOpenHelper;

	public ArticleProvider() {
	}

	@Override
	public boolean onCreate() {
		mOpenHelper = new ArticleDataBaseHelper(getContext());
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projectionIn, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder mBuilder = new SQLiteQueryBuilder();
		int match = URI_MATCHER.match(uri);
		switch (match) {
		case MESSAGES:
			mBuilder.setTables(TABLE_NAME);
			break;
		case MESSAGE_ID:
			mBuilder.setTables(TABLE_NAME);
			mBuilder.appendWhere("_id=");
			mBuilder.appendWhere(uri.getPathSegments().get(1));
			break;
		default:
			throw new IllegalArgumentException("Unknown Url :" + uri);
		}
		String orderBy;
		if (TextUtils.isEmpty(sortOrder)) {
			orderBy = ArticleConstants.DEFAULT_SORT_ORDER;
		} else {
			orderBy = sortOrder;
		}
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		Cursor ret = mBuilder.query(db, projectionIn, selection, selectionArgs,
				null, null, orderBy);
		if (ret == null) {
			infoLog("ArticleProvider Query Failed");
		} else {
			ret.setNotificationUri(getContext().getContentResolver(), uri);
		}
		return ret;
	}

	@Override
	public String getType(Uri uri) {
		int match = URI_MATCHER.match(uri);
		switch (match) {
		case MESSAGES:
			return ArticleConstants.CONTENT_TYPE;
		case MESSAGE_ID:
			return ArticleConstants.CONTENT_ITEM_TYPE;
		default:
			throw new IllegalArgumentException("Unknow Url");
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues initialValues) {
		if (URI_MATCHER.match(uri) != MESSAGES) {
			throw new IllegalArgumentException("cannot insert into Url : "
					+ uri);
		}
		ContentValues values = initialValues != null ? new ContentValues(
				initialValues) : new ContentValues();
		for (String colName : ArticleConstants.getRequireColumns()) {
			if (!values.containsKey(colName)) {
				throw new IllegalArgumentException("Missing column :" + colName);
			}
		}
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		long rowId = db.insert(TABLE_NAME, null, values);
		if (rowId < 0) {
			try {
				throw new SQLException("Failed to insert row into " + uri);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		Uri noteUri = ContentUris.withAppendedId(CONETNT_URI, rowId);
		getContext().getContentResolver().notifyChange(noteUri, null);
		return noteUri;
	}

	@Override
	public int delete(Uri uri, String where, String[] whereArgs) {
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count;
		switch (URI_MATCHER.match(uri)) {
		case MESSAGES:
			count = db.delete(TABLE_NAME, where, whereArgs);
			break;
		case MESSAGE_ID:
			String segment = uri.getPathSegments().get(1);
			if (TextUtils.isEmpty(where)) {
				where = "_id" + segment;
			} else {
				where = "_id" + segment + " AND (" + where + ")";
			}
			count = db.delete(TABLE_NAME, where, whereArgs);
			break;
		default:
			throw new IllegalArgumentException("Cannot delete from uri" + uri);
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	@Override
	public int update(Uri uri, ContentValues values, String where,
			String[] whereArgs) {
		int count;
		long rowId = 0;
		int match = URI_MATCHER.match(uri);
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		switch (match) {
		case MESSAGES:
			count = db.update(TABLE_NAME, values, where, whereArgs);
			break;
		case MESSAGE_ID:
			String segment = uri.getPathSegments().get(1);
			rowId = Long.parseLong(segment);
			count = db.update(TABLE_NAME, values, where, whereArgs);
			break;
		default:
			throw new UnsupportedOperationException("Cannot update Url " + uri);
		}
		infoLog("notifyChange() rowId : " + rowId + " url : " + uri);
		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	private static class ArticleDataBaseHelper extends SQLiteOpenHelper {
		// 数据库名称
		private static final String DATABASE_NAME = "article.db";
		// 数据库版本
		private static final int DATABASE_VERSION = 1;

		public ArticleDataBaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			// 建表
			infoLog("create new article table");
			db.execSQL("CREATE TABLE " + TABLE_NAME + "("
					+ ArticleConstants._ID
					+ " INTEGER PRIMARY KEY AUTOINCREMENT,"
					+ ArticleConstants.USER_NAME + " TEXT,"
					+ ArticleConstants.ARTICLE_TITLE + " TEXT,"
					+ ArticleConstants.ARTICLE_CONTENT + " TEXT,"
					+ ArticleConstants.ARTICLE_TIME + " TEXT,"
					+ ArticleConstants.ARTICLE_PIC + " TEXT);");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			switch (oldVersion) {
			default:
				db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
				onCreate(db);
			}
		}

	}

	//
	private static void infoLog(String data) {
		Log.i("night note article provider", data);
	}

	public static final class ArticleConstants implements BaseColumns {
		private ArticleConstants() {
		}

		public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nightnote.article";
		public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nightnote.article";
		// 默认的排序方式
		public static final String DEFAULT_SORT_ORDER = "_id ASC";
		// 文章作者
		public static final String USER_NAME = "user_name";
		// 文章标题
		public static final String ARTICLE_TITLE = "article_title";
		// 文章内容
		public static final String ARTICLE_CONTENT = "article_content";
		// 发表时间
		public static final String ARTICLE_TIME = "article_time";
		// 文章对应的图片
		public static final String ARTICLE_PIC = "article_pic";

		public static ArrayList<String> getRequireColumns() {
			ArrayList<String> tmpList = new ArrayList<String>();
			tmpList.add(USER_NAME);
			tmpList.add(ARTICLE_TITLE);
			tmpList.add(ARTICLE_TIME);
			tmpList.add(ARTICLE_CONTENT);
			tmpList.add(ARTICLE_PIC);
			return tmpList;
		}
	}
}
